package com.leoman.indexapi.service.Impl;

import com.leoman.creatordynamic.dao.CreatorDynamicDao;
import com.leoman.creatordynamic.entity.CreatorDynamic;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.exception.*;
import com.leoman.indexapi.service.LoginServiceApi;
import com.leoman.indexapi.service.UserTaskApiService;
import com.leoman.sensitivewords.dao.SensitiveWordsDao;
import com.leoman.sensitivewords.entity.SensitiveWords;
import com.leoman.user.dao.UserCollectDao;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.dao.UserLoginDao;
import com.leoman.user.dao.UserSignDao;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.entity.UserLogin;
import com.leoman.user.entity.UserSign;
import com.leoman.userapi.service.UserInfoService;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.userapi.service.UserLoginServiceApi;
import com.leoman.userapi.service.impl.UserInfoServiceImpl;
import com.leoman.utils.DateUtils;
import com.leoman.utils.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录
 * Created by Administrator on 2016/6/12.
 */
@Service
public class LoginServiceImplApi implements LoginServiceApi {

    @Autowired
    private UserLoginServiceApi userLoginService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private UserTaskApiService userTaskApiService;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private UserSignDao userSignDao;

    @Autowired
    private UserLoginDao userLoginDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private CreatorDynamicDao creatorDynamicDao;

    @Autowired
    private SensitiveWordsDao sensitiveWordsDao;

    @Override
    public Boolean loginCheck(UserLogin userLogin, String password) throws UsernamePasswordException, UserNotFindException {
        if (userLogin == null) {
            throw new UsernamePasswordException();
        }
        if (!userLogin.getPassword().equals(password)) {
            throw new UserNotFindException();
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional
    public UserInfo login(String username, String password, String registrationId) throws UsernamePasswordException, UserNotFindException, UserStatusErrorException {
        UserLogin userLogin = userLoginService.findByUsername(username);
        UserInfo userInfo = null;
        if (loginCheck(userLogin, password)) {
            userInfo = loginInit(userInfoDao.findOneByUserId(userLogin.getId()), registrationId);

            if (userInfo.getStatus().equals(Constant.USER_STATUS_FREEZE)) {
                throw new UserStatusErrorException();
            }

            userInfo.setPlayType(Constant.PLAY_TYPE_001);
        }

        if (null != userInfo && !userInfo.getIsCreator().equals(0) && !userInfo.getIsCreator().equals(3)) {
            addCreatorDynamicAndRegularlyDelete(userInfo);
        }

        return userInfo;
    }

    /**
     * 每日登录获取经验值
     *
     * @param userInfo 用户id
     */
    private void getExperience(UserInfo userInfo) {
        Integer check = userLoginDao.lastLoginDate(userInfo.getMobile(), DateUtils.getTimesmorning(), DateUtils.getTimesnight()).size();
        if (check == 0) {
            userIntegralService.changeIntegral(userInfo, "每日首次登录奖励50经验值", Constant.GETINTEGRAL_TYPE_FIRSTLOGIN);
        }
    }


    @Override
    @Transactional
    public UserInfo loginPlus(String openId, Integer type, String avater, Integer gender, String registrationId) throws ParamsErrorException, UserStatusErrorException, ThirdExistException {
        if (StringUtils.isEmpty(openId) || null == type) {
            throw new ParamsErrorException();
        }

        UserInfo userInfo = null;
        List<UserInfo> list;

        try {
            // 类型，1:微信 2:微博 3:QQ
            switch (type) {
                case 1:
                    list = userInfoService.findOneByWeixin(openId);
                    if (list.size() == 1) {
                        userInfo = list.get(0);
                    }
                    break;
                case 2:
                    list = userInfoService.findOneByWeibo(openId);
                    if (list.size() == 1) {
                        userInfo = list.get(0);
                    }
                    break;
                case 3:
                    list = userInfoService.findOneByQQ(openId);
                    if (list.size() == 1) {
                        userInfo = list.get(0);
                    }
                    break;
            }

            if (null == userInfo) {
                if (null == gender || StringUtils.isEmpty(avater)) {
                    throw new ParamsErrorException();
                }

                userInfo = new UserInfo();
                userInfo.setUserLogin(null);
                userInfo.setGender(gender);

                switch (type) {
                    case 1:
                        userInfo.setWeixin(openId);
                        userInfo.setHeadWeiXin(avater);
                        break;
                    case 2:
                        userInfo.setWeibo(openId);
                        userInfo.setHeadWeiBo(avater);
                        break;
                    case 3:
                        userInfo.setQq(openId);
                        userInfo.setHeadQQ(avater);
                        break;
                }

                if (StringUtils.isNotEmpty(registrationId)) {
                    userInfo.setRegistrationId(registrationId);
                }

                userInfoService.save(userInfo);

                userTaskApiService.setDefaultTask(userInfo.getId());
            } else {
                if (StringUtils.isNotEmpty(registrationId)) {
                    userInfo.setRegistrationId(registrationId);
                    userInfoService.save(userInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != userInfo) {
            if (userInfo.getStatus().equals(Constant.USER_STATUS_FREEZE)) {
                throw new UserStatusErrorException();
            }

            // 查询收藏数
            userInfo.setNum(userCollectDao.findListByUserId(userInfo.getId()).size());

            // 修改最后一次登录时间
            UserLogin userLogin = userInfo.getUserLogin();
            if (null != userLogin) {
                getExperience(userInfo);

                userLogin.setLastLoginDate(System.currentTimeMillis());
                userLoginService.update(userLogin);
            }

            userInfo.setPlayType(type);

            if (!userInfo.getIsCreator().equals(0) && !userInfo.getIsCreator().equals(3)) {
                addCreatorDynamicAndRegularlyDelete(userInfo);
            }
        }

        return userInfo;
    }

    @Override
    @Transactional
    public UserInfo loginPlus(String openId, Integer type, String avater, Integer gender, String registrationId, String mobile, String code, String password, String nickname) throws ParamsErrorException, UserStatusErrorException, ThirdExistException, SensitiveWordExistException, UserNicknameExistException {
        if (StringUtils.isEmpty(openId) || null == type || StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code) || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickname)) {
            throw new ParamsErrorException();
        }

        // 判断是否包含关键词
        List<SensitiveWords> sensitiveWordsList = sensitiveWordsDao.findByContentPlus("%" + nickname + "%");
        if (null != sensitiveWordsList && sensitiveWordsList.size() > 0) {
            throw new SensitiveWordExistException();
        }

        // 第三方用户信息
        UserInfo userInfo = null;
        List<UserInfo> list;

        try {
            // 类型，1:微信 2:微博 3:QQ
            switch (type) {
                case 1:
                    list = userInfoService.findOneByWeixin(openId);
                    if (list.size() > 0) {
                        userInfo = list.get(0);
                    }
                    break;
                case 2:
                    list = userInfoService.findOneByWeibo(openId);
                    if (list.size() > 0) {
                        userInfo = list.get(0);
                    }
                    break;
                case 3:
                    list = userInfoService.findOneByQQ(openId);
                    if (list.size() > 0) {
                        userInfo = list.get(0);
                    }
                    break;
            }

            UserInfo mobileUser = null;
            if (null == userInfo) {
                mobileUser = userInfoDao.findOneByMobile(mobile);
            }

            if (null == userInfo) {
                if (null != userInfoDao.findOneByNickname(nickname)) {
                    throw new UserNicknameExistException();
                }

                if (null == gender || StringUtils.isEmpty(avater)) {
                    throw new ParamsErrorException();
                }

                // 如果通过第三方找不到用户，但是通过手机号找得到用户信息，则将该第三方信息绑定到该手机号对应的用户信息中
                if (null != mobileUser) {
                    userInfo = mobileUser;

                    // 如果该用户没有昵称，则将当前昵称写入该用户信息中
                    if (StringUtils.isEmpty(userInfo.getNickname())) {
                        userInfo.setNickname(nickname);
                    }

                    // 如果该用户没有头像，则将当前头像写入该用户信息中
                    if (StringUtils.isEmpty(userInfo.getAvater())) {
                        String path = FileUtil.getUrlFromWeb(avater);
                        userInfo.setAvater(path);
                    }
                } else {
                    userInfo = new UserInfo();
                    userInfo.setUserLogin(null);
                    userInfo.setNickname(nickname);
                    userInfo.setGender(gender);
                    userInfo.setPassword(password);

                    String path = FileUtil.getUrlFromWeb(avater);
                    userInfo.setAvater(path);
                }

                userInfo.setMobile(mobile);

                switch (type) {
                    case 1:
                        userInfo.setWeixin(openId);
                        userInfo.setWeixinNickname(nickname);
                        userInfo.setHeadWeiXin(avater);
                        break;
                    case 2:
                        userInfo.setWeibo(openId);
                        userInfo.setWeiboNickname(nickname);
                        userInfo.setHeadWeiBo(avater);
                        break;
                    case 3:
                        userInfo.setQq(openId);
                        userInfo.setQqNickname(nickname);
                        userInfo.setHeadQQ(avater);
                        break;
                }

                if (StringUtils.isNotEmpty(registrationId)) {
                    userInfo.setRegistrationId(registrationId);
                }

                userInfoService.save(userInfo);

                userTaskApiService.setDefaultTask(userInfo.getId());
            } else {
                userInfo.setGender(gender);
                userInfo.setMobile(mobile);
                userInfo.setPassword(password);

                if (StringUtils.isNotEmpty(registrationId)) {
                    userInfo.setRegistrationId(registrationId);
                    userInfoService.save(userInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != userInfo && userInfo.getStatus().equals(Constant.USER_STATUS_FREEZE)) {
            throw new UserStatusErrorException();
        }

        // 查询收藏数
        if (null != userInfo) {
            userInfo.setNum(userCollectDao.findListByUserId(userInfo.getId()).size());

            // 修改最后一次登录时间
            UserLogin userLogin = userInfo.getUserLogin();
            if (null != userLogin) {
                userLogin.setLastLoginDate(System.currentTimeMillis());
                userLoginService.update(userLogin);
            }

            userInfo.setPlayType(type);

            if (!userInfo.getIsCreator().equals(0) && !userInfo.getIsCreator().equals(3)) {
                addCreatorDynamicAndRegularlyDelete(userInfo);
            }
        }

        return userInfo;
    }

    @Override
    public Integer signIn(Long userId) throws UserNotFindException, UserSignErrorException, UserStatusErrorException {
        String nowDate = DateUtils.dateToString(new Date(), "yyyy-MM-dd");
        UserInfo userInfo = UserInfoServiceImpl.getUserInfo(userInfoDao, userId);
        UserSign userSign = userSignDao.findOneByUserId(userId);

        // 如果没有签到记录，则新增一条签到记录
        if (null == userSign) {
            userSign = new UserSign();
            userSign.setUserInfo(userInfo);
            userSign.setSingDate(nowDate);
            userSign.setDays(1);
        } else {
            if (userSign.getSingDate().equals(nowDate)) {
                throw new UserSignErrorException();
            }

            // 如果不是连续签到，天数重置为1
            if (DateUtils.dateToString(DateUtils.dateAddDay(new Date(), -1), "yyyy-MM-dd").equals(userSign.getSingDate())) {
                userSign.setDays(userSign.getDays() + 1);
            } else {
                userSign.setDays(1);
            }

            userSign.setSingDate(nowDate);
        }

        userSignDao.save(userSign);

        // 进行每日签到任务
        userTaskApiService.finishTask(userId, Constant.USER_TASK_TYPE_001, false);

        return userSign.getDays();
    }

    @Override
    public void addCreatorDynamic(Long userId) {
        UserInfo userInfo = userInfoDao.findOne(userId);
        if (null != userInfo.getIsCreator() && !userInfo.getIsCreator().equals(0) & !userInfo.getIsCreator().equals(3)) {
            addCreatorDynamicAndRegularlyDelete(userInfo);
        }
    }

    @Override
    public Map<String, Object> checkLoginPlusInfo(String openId, Integer type) {
        Map<String, Object> map = new HashMap<>();
        Integer result;
        UserInfo userInfo = null;
        List<UserInfo> list;
        // 类型，1:微信 2:微博 3:QQ
        switch (type) {
            case 1:
                list = userInfoService.findOneByWeixin(openId);
                if (list.size() > 0) {
                    userInfo = list.get(0);
                }
                System.out.println("");
                break;
            case 2:
                list = userInfoService.findOneByWeibo(openId);
                if (list.size() > 0) {
                    userInfo = list.get(0);
                }
                break;
            case 3:
                list = userInfoService.findOneByQQ(openId);
                if (list.size() > 0) {
                    userInfo = list.get(0);
                }
                break;
        }

        if (null == userInfo) {
            result = 0;
        } else {
            if (StringUtils.isEmpty(userInfo.getMobile())) {
                result = 1;
            } else {
                result = 2;
            }
        }

        map.put("status", result);
        map.put("userId", null != userInfo ? userInfo.getId() : "");

        return map;
    }

    /**
     * 用户信息初始化
     */
    public UserInfo loginInit(UserInfo userInfo, String registrationId) {
        if (StringUtils.isNotEmpty(userInfo.getAvater())) {
            userInfo.setAvater(userInfo.getAvater().replaceAll(Configue.getUploadUrls(), ""));
        }
        if (StringUtils.isNotEmpty(registrationId)) {
            userInfo.setRegistrationId(registrationId);
        }
        userInfoService.save(userInfo);

        // 查询收藏数
        userInfo.setNum(userCollectDao.findListByUserId(userInfo.getId()).size());

        // 修改最后一次登录时间
        UserLogin userLogin = userInfo.getUserLogin();
        if (null != userLogin) {
            getExperience(userInfo);

            userLogin.setLastLoginDate(System.currentTimeMillis());
            userLoginService.update(userLogin);
        }

        return userInfo;
    }

    /**
     * 添加主创动态，正在看帖子，一小时后自动删除该动态
     */
    @Transactional
    private void addCreatorDynamicAndRegularlyDelete(UserInfo userInfo) {
        try {
            // 先判断该主创有没有动态，如果有，删除旧数据，同时新增一条正在看帖子的动态，一小时后自动删除
            List<CreatorDynamic> list = creatorDynamicDao.findListByCreatorIdPlus(userInfo.getId());
            if (null != list && list.size() > 0) {
                for (CreatorDynamic creatorDynamic : list) {
                    creatorDynamicDao.delete(creatorDynamic);
                }
            }

            System.out.println("******************************添加主创动态，一小时后自动删除******************************");
            final CreatorDynamic creatorDynamic = new CreatorDynamic();
            creatorDynamic.setUserInfo(userInfo);
            creatorDynamic.setStatus(1);
            creatorDynamic.setSource(0);
            creatorDynamic.setDate(DateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd"));
            creatorDynamicDao.save(creatorDynamic);

            // 一小时后自动删除该动态
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        // 设定时间为一个小时
                        Thread.sleep(1000 * 60 * 60);

                        // 删除动态
                        CreatorDynamic tempCD = creatorDynamicDao.findOne(creatorDynamic.getId());
                        if (null != tempCD) {
                            creatorDynamicDao.delete(creatorDynamic);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
